<?php

namespace app\bot\admin;

use app\common\builder\ZBuilder;
use app\bot\model\Message as MessageModel;

/**
 * 消息控制器
 */
class Message extends Index
{

    protected function initialize()
    {
        parent::initialize();
        if ($this->no_auth) {
            $this->error('权限不足！');
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 设置搜索参数
        $search = ['address' => '地址', 'type' => '类型'];

        // 获取查询条件
        $map = $this->getMap();

        $list_rows = input('list_rows', 20) >= 20 ? 20 : input('list_rows');
        // 数据列表
        $data_list = MessageModel::where($map)->order('date desc')->paginate($list_rows);
        // 分页数据
        $page = $data_list->render();

        $items = [
            ['id', 'ID'],
            ['bot_id', '机器人ID'],
            ['chat_id', '聊天ID'],
            ['chat_type', '聊天类型'],
            ['from_id', '发送人ID'],
            ['from_username', '发送人用户名'],
            // ['info', '详细', 'callback', function ($value) {
            //     return format_nice($value);
            // }, '', 'text-center'],
            ['date', '发送时间', 'datetime', '', 'Y-m-d H:i:s'],
            // ['create_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['right_button', '操作', 'btn']
        ];
        // 代付公司余额
        $send = [
            'title' => '发送',
            'icon' => 'fa fa-fw fa-check',
            'class' => 'btn btn-info',
            'href' => url('send')
        ];

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            //->hideCheckbox()
            ->setPageTitle('消息') // 设置页面标题
            ->setTableName('bot_message') // 设置数据表名
            ->setPrimaryKey('id') // 设置主键名为id
            ->setSearch($search) // 设置搜索参数
            ->addColumns($items)
            ->addTopButtons('add,enable,disable,delete') // 批量添加顶部按钮
            ->addTopButton('send', $send) // 添加按钮
            ->addRightButton('see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see', ['id' => '__id__'])], true)
            ->addRightButtons('edit,delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染页面
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Message');
            // 验证失败 输出错误信息
            if (true !== $result) {
                $this->error($result);
            }

            $token = $data['token'];
            $url = "https://api.telegram.org/bot{$token}/getUpdates";

            $resdata = go_curl($url, '', 'get', 10);
            $resarray = json_decode($resdata, true);

            if (isset($resarray['result'])) {

                foreach ($resarray['result'] as $key => $value) {

                    $v_k = array_keys($value);
                    $arr = [];
                    $arr[$v_k['0']] = $value['update_id'];
                    $arr['info'] = json_encode($value[$v_k['1']]);

                    if (isset($value[$v_k['1']]['from'])) {
                        $arr['from_id'] = $value[$v_k['1']]['from']['id'];
                        $arr['from_is_bot'] = $value[$v_k['1']]['from']['is_bot'] ?? 0;
                        $arr['from_first_name'] = $value[$v_k['1']]['from']['first_name'] ?? '';
                        $arr['from_last_name'] = $value[$v_k['1']]['from']['last_name'] ?? '';
                        $arr['from_username'] = $value[$v_k['1']]['from']['username'] ?? '';
                        $arr['from_language_code'] = $value[$v_k['1']]['from']['language_code'] ?? '';
                    }

                    if (isset($value[$v_k['1']]['chat'])) {
                        $arr['chat_id'] = $value[$v_k['1']]['chat']['id'] ?? '';
                        $arr['chat_type'] = $value[$v_k['1']]['chat']['type'] ?? '';
                        if ($arr['chat_type'] == 'supergroup' || $arr['chat_type'] == 'group') {
                            $arr['chat_title'] = $value[$v_k['1']]['chat']['title'];
                        }
                    }
                    if (isset($value[$v_k['1']]['text'])) {
                        //$arr['text'] = $value[$v_k['1']]['text'];
                    }
                    $arr['bot_id'] = strstr($token, ':', true);
                    $arr['create_time'] = time();
                    $arr['update_time'] = time();
                    $arr['date'] = $value[$v_k['1']]['date'];
                    $arr['id'] = $arr['date'] . $arr[$v_k['0']];
                    $find = MessageModel::where(['id' => $arr['id']])->find();

                    if ($find) {
                    } else {
                        try {
                            MessageModel::create($arr);
                        } catch (\Exception $e) {
                            payment_error_log(147, $arr, $e->getMessage());
                        }
                    }
                }
            }

            $this->success('新增成功', url('index'));
        }

        $items = [
            ['text', 'token', 'token', '根据token，统计聊天消息'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增') // 设置页面标题
            ->addFormItems($items)
            ->fetch();
    }

    /**
     * 查看
     * @param null $id 
     * @return mixed
     */
    public function see($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 获取数据
        $info = MessageModel::where('id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        $info['info'] = format_nice($info['info']);
        $items = [
            ['static', 'id', 'ID'],
            ['static', 'update_id', '更新ID'],
            ['textarea', 'info', '信息'],
            ['static', 'from_id', '发送人id'],
            ['radio', 'from_is_bot', '是不是机器人', '', ['不是', '是']],
            ['static', 'from_first_name', '发送人名字'],
            ['static', 'from_last_name', '发送人姓氏'],
            ['static', 'from_username', '发送人用户名'],
            ['static', 'from_language_code', '语言编码'],
            ['static', 'chat_id', '聊天ID'],
            ['static', 'chat_title', '标题，用于超级组、频道和群聊'],
            ['static', 'chat_type', '聊天类型，可以是私有、组、超级组或频道	'],
            ['static', 'date', '发送时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['static', 'bot_id', '机器人ID'],
            ['static', 'sort', '排序'],
            ['radio', 'status', '状态', '', ['禁用', '启用']],
            ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 
     * @return mixed
     */
    public function edit($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 获取数据
        $info = MessageModel::where('id', $id)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        $items = [
            ['static', 'id', 'ID', '', $id],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('信息') // 设置页面标题
            ->addHidden('id')
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 发送
     * @return mixed
     */
    public function send()
    {

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Message');
            // 验证失败 输出错误信息
            if (true !== $result) {
                $this->error($result);
            }

            $token = $data['token'];
            $url = "https://api.telegram.org/bot{$token}/getUpdates";

            $resdata = go_curl($url, '', 'get', 10);
            $resarray = json_decode($resdata, true);

            if (isset($resarray['result'])) {

                foreach ($resarray['result'] as $key => $value) {

                    $v_k = array_keys($value);
                    $arr = [];
                    $arr[$v_k['0']] = $value['update_id'];
                    $arr['info'] = json_encode($value[$v_k['1']]);

                    if (isset($value[$v_k['1']]['from'])) {
                        $arr['from_id'] = $value[$v_k['1']]['from']['id'];
                        $arr['from_is_bot'] = $value[$v_k['1']]['from']['is_bot'] ?? 0;
                        $arr['from_first_name'] = $value[$v_k['1']]['from']['first_name'] ?? '';
                        $arr['from_last_name'] = $value[$v_k['1']]['from']['last_name'] ?? '';
                        $arr['from_username'] = $value[$v_k['1']]['from']['username'] ?? '';
                        $arr['from_language_code'] = $value[$v_k['1']]['from']['language_code'] ?? '';
                    }

                    if (isset($value[$v_k['1']]['chat'])) {
                        $arr['chat_id'] = $value[$v_k['1']]['chat']['id'] ?? '';
                        $arr['chat_type'] = $value[$v_k['1']]['chat']['type'] ?? '';
                        if ($arr['chat_type'] == 'supergroup' || $arr['chat_type'] == 'group') {
                            $arr['chat_title'] = $value[$v_k['1']]['chat']['title'];
                        }
                    }
                    if (isset($value[$v_k['1']]['text'])) {
                        //$arr['text'] = $value[$v_k['1']]['text'];
                    }
                    $arr['bot_id'] = strstr($token, ':', true);
                    $arr['create_time'] = time();
                    $arr['update_time'] = time();
                    $arr['date'] = $value[$v_k['1']]['date'];
                    $arr['id'] = $arr['date'] . $arr[$v_k['0']];
                    $find = MessageModel::where(['id' => $arr['id']])->find();

                    if ($find) {
                    } else {
                        try {
                            MessageModel::create($arr);
                        } catch (\Exception $e) {
                            payment_error_log(147, $arr, $e->getMessage());
                        }
                    }
                }
            }

            $this->success('新增成功', url('index'));
        }

        $items = [
            ['text', 'token', 'token*', '根据token，使用不同机器人'],
            ['text', 'chat_id', '聊天ID*', '目标聊天的唯一标识符或目标频道的用户名（格式为@channelusername）'],
            ['textarea', 'text', '消息文本', '待发送的消息文本，实体解析后1-4096个字符'],
            ['text', 'message_thread_id', '消息线程ID', '论坛目标消息线程（主题）的唯一标识符；仅适用于论坛超级组'],
            ['text', 'parse_mode', '解析模式', '解析消息文本中的实体的模式。有关更多详细信息<code>HTML,Markdown,MarkdownV2</code>'],
            ['text', 'entities', '实体', '出现在消息文本中的特殊实体的 JSON 序列化列表，可以指定它而不是parse_mode'],
            ['text', 'disable_web_page_preview', '禁用网页预览', '禁用此消息中链接的链接预览'],
            ['text', 'disable_notification', '禁用通知', '默默地发消息。用户将收到无声音的通知。'],
            ['text', 'protect_content', '保护内容', '保护已发送消息的内容不被转发和保存'],
            ['text', 'reply_to_message_id', '回复消息ID', '如果消息是回复，则原始消息的ID'],
            ['text', 'allow_sending_without_reply', '允许发送而不回复', '如果即使未找到指定的回复消息也应发送消息，则传递True'],
            ['text', 'reply_markup', '回复标记', '附加接口选项。用于内联键盘、自定义回复键盘、删除回复键盘或强制用户回复的说明的JSON 序列化对象。'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增') // 设置页面标题
            ->addFormItems($items)
            ->fetch();
    }

    /**
     * 删除
     * @param array $record 
     * @return mixed
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用
     * @param array $record 
     * @return mixed
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用
     * @param array $record 
     * @return mixed
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record 
     * @return mixed
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids_delete = is_array($ids) ? '' : $ids;
        $data = MessageModel::where('id', 'in', $ids)->column('id');
        return parent::setStatus($type, ['bot_message_' . $type, 'bot_message', $ids_delete, UID, implode('、', $data)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id = input('post.pk', '');
        $field = input('post.name', '');
        $value = input('post.value', '');
        $data = MessageModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $data . ')，新值：(' . $value . ')';
        return parent::quickEdit(['bot_message_edit', 'bot_message', $id, UID, $details]);
    }
}
